import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Detail from '@/views/GoodsDetail'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 动态加载（路由懒加载）
const Login = () => import('@/views/Login')
const Layout = () => import('@/views/Layout')
const Detail = () => import('@/views/GoodsDetail')

// NProgress配置 ,nprogress 展示加载进度
NProgress.configure({ showSpinner: false })

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      titile: '登录'
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('../views/Layout/home.vue'),
        meta: {
          titile: '首页'
        }
      },
      {
        path: 'cate',
        name: 'Cate',
        component: () => import('../views/Layout/cate.vue'),
        meta: {
          titile: '分类'
        }
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('../views/Layout/cart.vue'),
        meta: {
          titile: '购物车'
        }
      },
      {
        path: 'mine',
        name: 'Mine',
        component: () => import('../views/Layout/mine.vue'),
        meta: {
          titile: '我的',
          requiresAuth: true //是否需要授权，是否登录
        }
      }
    ]
  },
  {
    path: '/detail',
    component: Detail,
    meta: {
      titile: '商品详情'
    }
  },
  {
    path: '/list',
    component: () => import('@/views/GoodLsit/index'),
    meta: {
      titile: '商品列表'
    }
  }
]

const router = new VueRouter({
  routes
})
// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 使用 nprogress 展示加载进度
  NProgress.start()
  if (to.meta?.requiresAuth) {
    /* 判断是否登录 */
    if (store.state.user.token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
// 全局后置导航守卫
router.afterEach((to, from) => {
  NProgress.done()
  document.title = to.meta.titile
})

export default router
